package org.snia.util;

import java.security.NoSuchAlgorithmException;


/**
 * uuid生成器
 * 
 * @author c90003207
 * 
 */
public class JuuidUtils {
	private final static String nodePathTemplate = "xxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxxx";
	private final static String uuidPathTemplate = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

	/**
	 * 根据path生成uuid
	 * 
	 * @param path
	 *            文件路径
	 * @return uuid
	 * @throws NoSuchAlgorithmException 
	 *             异常
	 */
	public static String getuuid(String path) {
		StringBuffer sb = new StringBuffer();
		String temp = null;
		try {
			temp = MD5Util.getMD5(path);
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		char[] chars = temp.toCharArray();
		int cnt = 0;
		for (int i = 0; i < uuidPathTemplate.length(); i++) {
			char ch = uuidPathTemplate.charAt(i);
			if (ch == 'x' && cnt < chars.length) {
				ch = chars[cnt++];
				if (ch == '-') {
					ch = chars[cnt++];
				}
			}
			sb.append(ch);
		}
		return sb.toString();
	}

	/**
	 * 根据uuid生成存储目录结构
	 * 
	 * @param uuid
	 *            文件uuid
	 * @return 文件路径
	 * @throws Exception
	 *             异常
	 */
	public static String getuuidPath(String uuid) {
		StringBuffer uuidsb = new StringBuffer();
		String s = uuid;
		char[] chars = s.toCharArray();
		int cnt = 0;
		for (int i = 0; i < nodePathTemplate.length(); i++) {
			char ch = nodePathTemplate.charAt(i);
			if (ch == 'x' && cnt < chars.length) {
				ch = chars[cnt++];
				if (ch == '-') {
					ch = chars[cnt++];
				}
			}
			uuidsb.append(ch);
		}
		return uuidsb.toString();
	}

}
